package com.ice.framework.http

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class Http {
    var baseUrl = ""

    companion object {

        var mGetHeaderCallBack:(()->Map<String,String>)?=null
        fun config(
            baseUrl: String,
            getHeaderCallBack:()->Map<String,String>
        ): Http {
            val http = Http()
            http.baseUrl = baseUrl
            mGetHeaderCallBack=getHeaderCallBack
            return http
        }

    }

    inline fun <reified T> instance(): T {
        val clientBuilder = OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
        clientBuilder.addInterceptor {
            val builder = it.request().newBuilder()
            val headers= mGetHeaderCallBack?.invoke()
            headers?.forEach { item ->
                builder.addHeader(item.key, item.value)
            }
            val request=builder.build()
            return@addInterceptor it.proceed(request)
        }
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        clientBuilder.addInterceptor(loggingInterceptor)
        val okHttpClient = clientBuilder.build()
        okHttpClient.dispatcher().maxRequestsPerHost = 1
        return Retrofit.Builder()
            .baseUrl(this.baseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(T::class.java)
    }
}